package com.hwf.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class HwfBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println("初始化前");
        if(beanName.equals("userService")){
            ((UserService)bean).setName("hello world");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanNme) {
        System.out.println("初始化后");
        if(beanNme.equals("userService")){
            //模拟aop返回代理对象
            Object proxyInstance = Proxy.newProxyInstance(HwfBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("代理逻辑......");
                    return method.invoke(bean,args);
                }
            });
            return proxyInstance; //返回代理对象

        }
        return bean;
    }
}
